#include "sgu.h"

SGU_NS_BEGIN


//*********** TextOutputFile
void TextOutputFile::writeChar(char k)
{
	_file.resize(_ptr+1);
	_file.ptr()[_ptr] = k;
	++_ptr;
}

void TextOutputFile::write(char k)
{
	ASSERT(valid(k));
	writeChar(k);	
}

void TextOutputFile::write(const char * str) 
{
	while(*str)
	{
		write(*str);
		++str;
	}
}

void TextOutputFile::writeln(const char * str) 
{
	write(str);
	writeChar('\n');
}

void TextOutputFile::writeln() 
{
	writeChar('\n');
}


//*********** TextInputFile

int TextInputFile::readChar()
{
	if(_ptr>=_file.size())
		return EOF;
	int k = (unsigned char)_file.cptr()[_ptr];	
	++_ptr;
	return k;
}


bool TextInputFile::read(std::string & str)
{
	str.clear();
	while(true)
	{
		int k = readChar();
		if(k==EOF) return false;
		if(k=='\n') break;
		str += validate(k);
	}
	return true;
}

std::string TextInputFile::read() // diversa semanticamente per l'ultima linea
{
	std::string str;
	while(true)
	{
		int k = readChar();
		if(k==EOF)
		{
			if(str.empty()) THROWSGUFUNCEXCEPTION("/eof");
			else return str;
		}
		if(k=='\n') break;
		str += validate(k);
	}
	return str;
}


SGU_NS_END
